package xhwl.insurance.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import xhwl.android.common.CommonConstants;
import xhwl.android.common.http.bean.ResponseError;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.manager.JPushMgr;
import xhwl.android.common.util.CommonAppUtil;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.android.common.view.VerificationCodeInput;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.Constant;
import xhwl.insurance.R;
import xhwl.insurance.event.LoginEvent;
import xhwl.insurance.http.api.GetVerifyCodeApi;
import xhwl.insurance.http.api.LoginApiV2;
import xhwl.insurance.http.api.RegJPushApi;
import xhwl.insurance.http.bean.resp.LoginRespV2;
import xhwl.insurance.http.bean.resp.SmsResp;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.util.AppUtil;
import xhwl.insurance.util.SpUtil;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


/**
 * 验证码注册界面
 * Created by admin on 2017-07-13.
 */

public class LoginAuthCodeActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = LoginAuthCodeActivity.class.getSimpleName();
    public static final String EXTRA_PHONE = "phone";
    private TextView tvPhone;
    private TextView tvSMSCode;//获取短信验证码
    //    private android.widget.EditText etSmsCode;//验证码输入框
    private TextView tvVoiceCode;//获取语音验证码
    private TextView tvPhoneNumber;

    String phone;
    String strSms = "获取验证码", strSms1 = "重新获取验证码", strVoice = "语音验证码";
    int retry = 0;
    boolean waiting = false;

    VerificationCodeInput input;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        phone = getIntent().getStringExtra(EXTRA_PHONE);
        setContentView(R.layout.activity_login_authcode);
    }

    @Override
    public void initViews() {
        initTitleViews();
        this.tvVoiceCode = (TextView) findViewById(R.id.tvVoiceCode);
        this.tvPhoneNumber= (TextView) findViewById(R.id.tvPhoneNumber);
//        this.etSmsCode = (EditText) findViewById(R.id.etSmsCode);
        this.tvSMSCode = (TextView) findViewById(R.id.tvSMSCode);
        this.tvPhone = (TextView) findViewById(R.id.tvPhone);
        this.tvPhone.setText("手机号");
        this.tvPhoneNumber.setText(phone);
        this.tvVoiceCode.setText(strVoice);
        this.tvSMSCode.setText(strSms);
        input = (VerificationCodeInput) findViewById(R.id.verificationCodeInput);
        input.setOnCompleteListener(new VerificationCodeInput.Listener() {
            @Override
            public void onComplete(String content) {
                Log.d(TAG, "完成输入：" + content);
                // TODO: 2017-07-13 手机号验证码登录
//                HttpHelper.getInstance().authCodeLoginorRegist(mContext,phone,content, PublicStatic.lat+"",PublicStatic.lon+"",RegistAuthCodeActivity.this);
                BaseApi api = new LoginApiV2(phone, content, CommonAppUtil.getImei(mContext));
                HttpManager.getInstance().dealHttp(LoginAuthCodeActivity.this, api, new OnNextListener<String>() {
                    @Override
                    public void onNext(String str) {
                        LoginRespV2 resp = new Gson().fromJson(str, LoginRespV2.class);
                        if (!StringUtil.isEmpty(resp.member_id)) {
                            SharedPreferences.Editor editor = SPUtil.getPersonInfoSp().edit();
                            editor.putString(SPUtil.SPPersonInfo.MEMBER_ID, resp.member_id);
                            editor.putString(SPUtil.SPPersonInfo.LINK_MOBILE, phone);
                            editor.commit();
                            EventBus.getDefault().post(new LoginEvent(true));
                            ToastUtil.showToast(mContext, "登录成功");
                            registJPushId(resp.member_id);
                            startActivity(new Intent(mContext, MainActivity.class)
                                    .putExtra("BACK_STATE","0"));
                            finish();
                        } else {
                            ResponseError error = new Gson().fromJson(str, ResponseError.class);
                            if (error != null && "00014".equals(error.error_code)) {
                                ToastUtil.showToast(mContext, "验证码错误");

                            } else {
                                ToastUtil.showToast(mContext, error.getErrorMsg());

                            }
                            input.clear();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void initListener() {
        this.tvSMSCode.setOnClickListener(this);
        this.tvVoiceCode.setOnClickListener(this);
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("登录HMO管家");
    }

    @Override
    protected void processOper() {
        if (!StringUtil.isEmpty(phone) && tvSMSCode.isEnabled()) {//直接获取验证码
            this.tvSMSCode.performClick();
        }
    }

    @Override
    public void loadData() {

    }

    String type = CommonConstants.AUTHCODE_SMS;
    private CountDownTimer timer = new CountDownTimer(Constant.AUTH_TIME_ALL, Constant.AUTH_TIME_INTERAL) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvSMSCode.setEnabled(false);
            waiting = true;
            tvSMSCode.setTextColor(getResources().getColor(R.color.main_text_color));
            tvVoiceCode.setTextColor(getResources().getColor(R.color.main_text_color));
            tvSMSCode.setText("("+millisUntilFinished / 1000 + "秒)");
        }

        @Override
        public void onFinish() {
            tvSMSCode.setEnabled(true);
            waiting = false;
            tvSMSCode.setTextColor(getResources().getColor(R.color.login_text_color));
            tvVoiceCode.setTextColor(getResources().getColor(R.color.login_text_color));
            tvSMSCode.setText(strSms1);
            tvVoiceCode.setText(strVoice);

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvSMSCode:
                retry++;
                if (retry == 3) {
                    ToastUtil.showToast(mContext, "收不到验证码？请点击语音验证码获取验证码");
                }
                type = CommonConstants.AUTHCODE_SMS;

                getAuthCode();
                break;
            case R.id.tvVoiceCode:
                if (waiting) {
                    ToastUtil.showToast(mContext, "获取验证码中，请稍候");
                    return;
                }
                retry = 0;
                type = CommonConstants.AUTHCODE_VOICE;

                getAuthCode();

                break;
        }
    }

    private void getAuthCode() {
        timer.start();
        String post_ip = AppUtil.getIp(mContext);
       GetVerifyCodeApi api = new GetVerifyCodeApi(phone, type, post_ip);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<SmsResp>() {
            @Override
            public void onNext(SmsResp resp) {
                if (!StringUtil.isEmpty( resp.phone_code)) {
                    tvPhone.setText("验证码已发送至");
//                    ToastUtil.showToast(mContext, "验证码已发送");
                } else {
                    cancleTimer();
                    if(!StringUtil.isEmpty( resp.message)){
                        ToastUtil.showToast(mContext, resp.message,true);
                    }
                    else
                    {
                        ToastUtil.showToast(mContext, "验证码发送失败",true);
                    }
                }

            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                cancleTimer();
            }
        });

    }

    private void cancleTimer() {
        timer.cancel();
        tvSMSCode.setEnabled(true);
        waiting = false;
        tvSMSCode.setTextColor(getResources().getColor(R.color.login_text_color));
        tvVoiceCode.setTextColor(getResources().getColor(R.color.login_text_color));
        tvSMSCode.setText(strSms1);
        tvVoiceCode.setText(strVoice);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancleTimer();
    }

    private void registJPushId(final String memberId) {
        JPushMgr.getInstance().registJPushId(mContext, new JPushMgr.RegistJpushCallback() {

            @Override
            public void onResult(boolean result, final String msg) {
                // TODO Auto-generated method stub
                if (result)
                {
                    String appKey= AppUtil.getMetadata(mContext, Constant.JPUSH_APP_KEY);
                    RegJPushApi api=new RegJPushApi(memberId,msg,appKey);
                    HttpManager.getInstance().dealHttp(LoginAuthCodeActivity.this, api, new OnNextListener<HttpResp>() {
                        @Override
                        public void onNext(HttpResp resp) {
                            if (resp!=null&&resp.isOk()) {
                                XHLog.e("regist jpush id success id=" + msg);
                                SpUtil.putBoolean(SpUtil.IS_JPUSH_REGIST,true);
                                JPushInterface.resumePush(mContext.getApplicationContext());
                            } else {
                                XHLog.e("regist jpush id fail id=" + msg);
                            }
                        }
                    });
                }
            }
        });
    }
}
